const db = require("./db/index");

const sd = require("silly-datetime");

const { filterData } = require("./utils/analysisDataBuffer");
const { handleHumidtyDataHex2Dec } = require("./utils/conversion");
const deveui = `8D00000051040013`;
const mock_data = require("./data.json");
const { insertHumidty } = require("./db/humidty");
const { getSensor, getDataType } = require("./mqtt_data_source/common");

//1.字符串 转 JSON 对象
//2.JSON.data base64解码 转Buffer对象
let buffer = Buffer.from(mock_data.data, "base64");
//3. Buffer转Array对象，掐头（4个元素）去尾（2个元素） 保留最终有效数据
let buffer_copy = Uint8Array.prototype.slice
  .call(buffer)
  .slice(4, buffer.length - 2);

async function insertHumidtyData(deveui, buffer) {
  //1.获取终端deveui下的所有传感器
  let sensor_list = (await getSensor(deveui)) ?? [];
  sensor_list.forEach(async (item) => {
    //2.获取传感器上传的数据类型
    let type_data = await getDataType(item.type_data_id);
    //3.找到匹配上对应的类型的传感器，根据传感器上的485地址，解析buffer
    if (type_data[0].type == "温湿度" || type_data[0].type == "湿度") {
      let tt = filterData(buffer, item.address);
      //4.将解析之后的数据，根据传感器使用文档，处理16进制的数据，得到的是最后的温度的数据
      let temperature_data_value = handleHumidtyDataHex2Dec(tt);
      //5.准备数据的其他项：sensor_id | upload_time | data_unit
      let sensor_id = item.id;
      let upload_time = sd.format(new Date(), "YYYY-MM-DD HH:mm:ss");
      let data_unit = `RH`;
      // 6.sql插入语句
      insertHumidty({
        sensor_id,
        temperature_data_value,
        upload_time,
        data_unit,
      });
    }
  });
}
insertHumidtyData(deveui, buffer_copy);
